package br.pucrio.inf.lac.konoha.hyuga.core;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;

import org.apache.log4j.Logger;

import com.sun.management.OperatingSystemMXBean;

public class MonitoringAgent {

    /** LOGGER **/    
    private static Logger LOGGER = Logger.getLogger(MonitoringAgent.class.getCanonicalName());

    // Singleton Instance
    protected static MonitoringAgent instance;
    
    // JMX Beans
    private OperatingSystemMXBean operatingSystemMXBean;
    private MemoryMXBean memoryMXBean;
    
    private MonitoringAgent() {
        operatingSystemMXBean =  ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        memoryMXBean = (MemoryMXBean) ManagementFactory.getMemoryMXBean();
    }
    
    /** 
     * MonitoringAgent singleton.
     * @return a Monitoring Agent with cpu, memory, and other resources information.
     */
    public synchronized static MonitoringAgent getInstance() {
        if (instance == null) 
            instance = new MonitoringAgent(); // TODO: Double locking

        return instance;
    }
    
    public double getCpuUsage() {
        return operatingSystemMXBean.getProcessCpuLoad();
    }

    public double getSysUsage() {
        return operatingSystemMXBean.getSystemCpuLoad();
    }
    
    public double getMemoryUsage() {
        return (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory()) / 1024 / 1024;
        //convert from Bytes to MB
    }
}
